﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;

namespace SQLProxy
{
    class Program
    {
        static void Main(string[] args)
        {
            string IP = SearchGoodIP(Dns.GetHostEntry(Dns.GetHostName()).AddressList);
            Console.WriteLine("- DataBase Proxy - address: " + IP + " -");
            // creates the global listener
            Listener list = new Listener();
            TcpListener tl = list.createListener();
            tl.Start();

            while (true)
            {
                ClientInteraction cInt;
                Socket clientSocket = tl.AcceptSocket();

                if (clientSocket.Connected)
                {
                    cInt = new ClientInteraction(clientSocket);
                }
            }
        }

        private static string SearchGoodIP(IPAddress[] ips)
        {
            //Magic...
            string regexpPattern =
                @"^" +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\." +
                @"(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])" +
                @"$";

            foreach (IPAddress ip in ips)
            {
                Match m = Regex.Match(ip.ToString(), regexpPattern);
                if (m.Success == true)
                {
                    return ip.ToString();
                }
            }

            return "IP problem";

        }
    }
}
